package roles;

import avenue.MyWindowEvent;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import javax.persistence.EntityManager;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import model.DBManager;
import model.RolePermission;
import model.UserRole;

public class ListRolesForm extends javax.swing.JFrame {

    /**
     * Creates new form ListUsersForm
     */
    public ListRolesForm() {
        em = DBManager.em;
        if ( !em.getTransaction().isActive()){
            em.getTransaction().begin();
        }
        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        bindingGroup = new org.jdesktop.beansbinding.BindingGroup();

        userRoleQuery = java.beans.Beans.isDesignTime() ? null : em.createQuery("select ur from  UserRole ur");
        userRoleList = java.beans.Beans.isDesignTime() ? java.util.Collections.emptyList() : org.jdesktop.observablecollections.ObservableCollections.observableList(userRoleQuery.getResultList());
        editRoleButton = new javax.swing.JButton();
        deleteRoleButton = new javax.swing.JButton();
        newRoleButton = new javax.swing.JButton();
        userRoleScrollPane = new javax.swing.JScrollPane();
        userRoleTable = new javax.swing.JTable();
        userRoleLabel = new javax.swing.JLabel();
        cancelButton = new javax.swing.JButton();
        saveButton = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
        setTitle("Διαχείριση Ρόλων");

        editRoleButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/edit1.png"))); // NOI18N
        editRoleButton.setText("Επεξεργασία");
        editRoleButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                editRoleButtonActionPerformed(evt);
            }
        });

        deleteRoleButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/remove.gif"))); // NOI18N
        deleteRoleButton.setText("Διαγραφή");
        deleteRoleButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                deleteRoleButtonActionPerformed(evt);
            }
        });

        newRoleButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/add.gif"))); // NOI18N
        newRoleButton.setText("Νέος");
        newRoleButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                newRoleButtonActionPerformed(evt);
            }
        });

        org.jdesktop.swingbinding.JTableBinding jTableBinding = org.jdesktop.swingbinding.SwingBindings.createJTableBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, userRoleList, userRoleTable, "userRoleList");
        org.jdesktop.swingbinding.JTableBinding.ColumnBinding columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${roleName}"));
        columnBinding.setColumnName("Role Name");
        columnBinding.setColumnClass(String.class);
        columnBinding.setEditable(false);
        bindingGroup.addBinding(jTableBinding);
        jTableBinding.bind();
        userRoleScrollPane.setViewportView(userRoleTable);

        userRoleLabel.setText("Ρόλοι");

        cancelButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/cancel.gif"))); // NOI18N
        cancelButton.setText("Ακυρο");
        cancelButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cancelButtonActionPerformed(evt);
            }
        });

        saveButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/save.gif"))); // NOI18N
        saveButton.setText("Αποθήκευση");
        saveButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                saveButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(userRoleScrollPane, javax.swing.GroupLayout.DEFAULT_SIZE, 790, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(userRoleLabel)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(newRoleButton)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(deleteRoleButton)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(editRoleButton))
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(cancelButton)
                                .addGap(18, 18, 18)
                                .addComponent(saveButton)))
                        .addGap(0, 0, Short.MAX_VALUE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(32, 32, 32)
                .addComponent(userRoleLabel)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(userRoleScrollPane, javax.swing.GroupLayout.PREFERRED_SIZE, 105, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(newRoleButton)
                    .addComponent(deleteRoleButton)
                    .addComponent(editRoleButton))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 42, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(cancelButton)
                    .addComponent(saveButton))
                .addContainerGap())
        );

        bindingGroup.bind();

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void newRoleButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_newRoleButtonActionPerformed

       ur = new UserRole();
       em.persist(ur);
       EditRoleForm erf = new EditRoleForm(ur,true);
       
       erf.setVisible(true);
       thisFrame=this;
       thisFrame.setEnabled(false);
       //************
        erf.addWindowListener(new WindowListener() {
            public void windowClosed(WindowEvent arg0) {
                System.out.println("Window close event occur");
               if (((MyWindowEvent)arg0).exitAndSave){
                    
                    
                    userRoleList.add(ur);
                    int row = userRoleList.size() - 1;
        
                    userRoleTable.setRowSelectionInterval(row, row);
                    userRoleTable.scrollRectToVisible(userRoleTable.getCellRect(row, 0, true));
                    thisFrame.setEnabled(true);
                }
                else{
                    thisFrame.setEnabled(true);
                }
            }
            public void windowActivated(WindowEvent arg0) {
                System.out.println("Window Activated");
            }
            public void windowClosing(WindowEvent arg0) {
                System.out.println("Window Closing");
            }
            public void windowDeactivated(WindowEvent arg0) {
                System.out.println("Window Deactivated");
            }
            public void windowDeiconified(WindowEvent arg0) {
                System.out.println("Window Deiconified");
            }
            public void windowIconified(WindowEvent arg0) {
                System.out.println("Window Iconified");
            }
            public void windowOpened(WindowEvent arg0) {
                System.out.println("Window Opened");
            }
        });
    }//GEN-LAST:event_newRoleButtonActionPerformed

    private void deleteRoleButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_deleteRoleButtonActionPerformed
        
        s = userRoleTable.getSelectedRow();
        if (s >= 0) {
            ur = userRoleList.get(userRoleTable.convertRowIndexToModel(s));
            // Έλεγχος για το αν ο ρόλος μπορεί όντως να διαγραφεί
            if (ur.getAppUserList().size() == 0) {
                // Επιβεβαίωση της διαγραφής
                int choice = JOptionPane.showConfirmDialog(this,
                                          "Διαγραφή του συγκεκριμένου ρόλου;",
                                          "Επιβεβαίωση διαγραφής ρόλου",
                                          JOptionPane.YES_NO_OPTION);
                
                if (choice != 0)
                    return;
                
                userRoleList.remove(ur);
                for (RolePermission rp : ur.getRolePermissionList()) { 
                     em.remove(rp);
                }
                em.remove(ur);
            } else { 
                JOptionPane.showMessageDialog(this, "Ο ρόλος δεν μπορεί να διαγραφεί (υπάρχουν χρήστες που του αναλογούν).",
                                          "Σφάλμα",JOptionPane.ERROR_MESSAGE);
            }
        }
    }//GEN-LAST:event_deleteRoleButtonActionPerformed

    private void editRoleButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_editRoleButtonActionPerformed

        s = userRoleTable.getSelectedRow();
        
        if (s >= 0) {
            
            ur = userRoleList.get(userRoleTable.getSelectedRow());
            EditRoleForm erf = new EditRoleForm(ur,false);
            erf.setVisible(true);
            thisFrame = this;
            thisFrame.setEnabled(false);
       
       //************
        erf.addWindowListener(new WindowListener() {
            public void windowClosed(WindowEvent arg0) {
                System.out.println("Window close event occur");
               if (((MyWindowEvent)arg0).exitAndSave){
                    
                    
                    userRoleTable.setRowSelectionInterval(s, s);
                    userRoleTable.scrollRectToVisible(userRoleTable.getCellRect(s, 0, true));
                    thisFrame.setEnabled(true);
                }
                else{
                    thisFrame.setEnabled(true);
                    for (RolePermission pr : ur.getRolePermissionList()) { 
                         em.refresh(pr);
                    }
                    em.refresh(ur);
                }
            }
            public void windowActivated(WindowEvent arg0) {
                System.out.println("Window Activated");
            }
            public void windowClosing(WindowEvent arg0) {
                System.out.println("Window Closing");
            }
            public void windowDeactivated(WindowEvent arg0) {
                System.out.println("Window Deactivated");
            }
            public void windowDeiconified(WindowEvent arg0) {
                System.out.println("Window Deiconified");
            }
            public void windowIconified(WindowEvent arg0) {
                System.out.println("Window Iconified");
            }
            public void windowOpened(WindowEvent arg0) {
                System.out.println("Window Opened");
            }
        });
        }
    }//GEN-LAST:event_editRoleButtonActionPerformed

    private void cancelButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelButtonActionPerformed
        em.getTransaction().rollback();
        em.getTransaction().begin();
        dispose();
    }//GEN-LAST:event_cancelButtonActionPerformed

    private void saveButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_saveButtonActionPerformed
        em.getTransaction().commit();
        em.getTransaction().begin();
        dispose();
    }//GEN-LAST:event_saveButtonActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton cancelButton;
    private javax.swing.JButton deleteRoleButton;
    private javax.swing.JButton editRoleButton;
    private javax.swing.JButton newRoleButton;
    private javax.swing.JButton saveButton;
    private javax.swing.JLabel userRoleLabel;
    private java.util.List<UserRole> userRoleList;
    private javax.persistence.Query userRoleQuery;
    private javax.swing.JScrollPane userRoleScrollPane;
    private javax.swing.JTable userRoleTable;
    private org.jdesktop.beansbinding.BindingGroup bindingGroup;
    // End of variables declaration//GEN-END:variables
    UserRole ur;
    EntityManager em;
    JFrame thisFrame;
    int s;
}
